const install = (Vue, vm) => {
	// 图片转bs64
	const local_img2base64 = (imgPath, dir) => {
		// 因为是异步事件 用promise完成内部定义 再外部调用此函数时使用async await
		return new Promise(function(resolve, reject) {
			// uni.showToast({
			// 	title:`图片方向: ${dir}`
			// })
			// 创建image 对象
			let Img = new Image()
			Img.setAttribute('crossOrigin', 'Anonymous')
			Img.src = imgPath
			console.log('width', Img)
			console.log('height', Img.height)
			Img.onload = () => {
				console.log('------Img.onload--------')
				//要先确保图片完整获取到，这是个异步事件
				//创建canvas元素
				let canvas = document.createElement('canvas')
				let ctx = canvas.getContext('2d')
				//确保canvas的尺寸和图片一样
				let width = Img.width / 2
				let height = Img.height / 2

				canvas.width = width
				canvas.height = height

				//将图片绘制到canvas中
				ctx.drawImage(Img, 0, 0, canvas.width, canvas.height)
				console.log('switch方向 = ', dir)
				switch (dir) {
					case 6:
						ctx.transform(0, 1, -1, 0, height, 0)
						console.log('画布旋转：逆时针90度')
						break
					case 8:
						ctx.transform(0, -1, 1, 0, 0, width)
						console.log('画布旋转：顺时针回转90度')
						break

					default:
						console.log('North 不旋转')
						break
				}

				let dataURLs = canvas.toDataURL('image/jpeg', 0.5)

				resolve(dataURLs)
			}
		})
	}

	// 提交认证信息上传照片
	const auth_img2base64 = (imgPath, dir) => {
		// 因为是异步事件 用promise完成内部定义 再外部调用此函数时使用async await
		return new Promise(function(resolve, reject) {
			// uni.showToast({
			// 	title:`图片方向: ${dir}`
			// })
			// 创建image 对象
			let Img = new Image()
			Img.setAttribute('crossOrigin', 'Anonymous')
			Img.src = imgPath
			console.log('width', Img)
			console.log('height', Img.height)
			Img.onload = () => {
				console.log('------Img.onload--------')
				//要先确保图片完整获取到，这是个异步事件
				//创建canvas元素
				let canvas = document.createElement('canvas')
				let ctx = canvas.getContext('2d')
				//确保canvas的尺寸和图片一样
				let width = Img.width
				let height = Img.height

				canvas.width = width
				canvas.height = height

				//将图片绘制到canvas中
				ctx.drawImage(Img, 0, 0, canvas.width, canvas.height)

				switch (dir) {
					case 6:
						ctx.transform(0, 1, -1, 0, height, 0)
						console.log('←回转90度')
						break
					case 8:
						ctx.transform(0, -1, 1, 0, 0, width)
						console.log('→回转90度')
						break

					default:
						console.log('不旋转')
						break
				}

				let dataURLs = canvas.toDataURL('image/jpeg', 0.8)

				resolve(dataURLs)
			}
		})
	}

	// 提交bug上传图片
	const bug_img2base64 = (imgPath, dir) => {
		// 因为是异步事件 用promise完成内部定义 再外部调用此函数时使用async await
		return new Promise(function(resolve, reject) {
			// uni.showToast({
			// 	title:`图片方向: ${dir}`
			// })
			// 创建image 对象
			let Img = new Image()
			Img.setAttribute('crossOrigin', 'Anonymous')
			Img.src = imgPath
			console.log('width', Img)
			console.log('height', Img.height)
			Img.onload = () => {
				console.log('------Img.onload--------')
				//要先确保图片完整获取到，这是个异步事件
				//创建canvas元素
				let canvas = document.createElement('canvas')
				let ctx = canvas.getContext('2d')
				//确保canvas的尺寸和图片一样
				let width = Img.width
				let height = Img.height

				canvas.width = width
				canvas.height = height
				//将图片绘制到canvas中
				ctx.drawImage(Img, 0, 0, canvas.width, canvas.height)
				switch (dir) {
					case 6:
						ctx.transform(0, 1, -1, 0, height, 0)
						console.log('←回转90度')
						break
					case 8:
						ctx.transform(0, -1, 1, 0, 0, width)
						console.log('→回转90度')
						break

					default:
						console.log('不旋转')
						break
				}

				let dataURLs = canvas.toDataURL('image/jpeg', 0.8)
				resolve(dataURLs)
			}
		})
	}

	// 登录检查
	const login_check = (pageUrl) => {
		console.log('登录检查')
		return new Promise(function(resolve, reject) {
			console.log('vm.vuex_request_token', vm.vuex_request_token)
			// 跳转到登录界面 拿code
			if (vm.vuex_request_token == 'no_value') {
				let index = pageUrl.indexOf('code')
				// 跳转到登录页面
				if (index == -1) {
					// 跳转到登录界面
					let url = window.location.href
					console.log('url=!!!!!!!!!=====', url)
					vm.$u.api
						.get_wechat_login_link({
							current_url: pageUrl
							// current_url: vm.vuex_index_page
						})
						.then((res) => {
							if (res.code == 200) {
								window.location.href = res.data.oauth_url
							} else {
								console.log('服务器返回登录链接失败')
								reject()
							}
						})
				}
				// 从登录界面返回当前界面
				if (index != -1) {
					console.log('pageUrl=', pageUrl)
					const str = pageUrl.substr(pageUrl.indexOf("?") + 1, pageUrl.length)
					const params = str.split('&')
					let codeStr = "";
					params.filter((item) => {
						if(item.search("code=") !== -1) {
							codeStr = item;
						}
					})
					let code = codeStr.split('#')[0].split('=')[1];
					vm.$u.api.use_wechatcode_exchange_token({
							code: code
						}).then((res) => {
							if (res.code == 200) {
								console.log('获取token成功', res);
								vm.$u.vuex('vuex_request_token', res.data.request_token);
								vm.$u.vuex('vuex_refresh_token', res.data.refresh_token);
								(async () => {
									console.log('等待异步任务')
									await vm.$u.utils.update_user_locatin();
									// 获取用户信息
									vm.$u.api.get_user_social_info().then((res) => {
										if (res.code == 200) {
											uni.setStorage({
												key: 'pageUrl',
												data: window.location.href
											})
											console.log('用户社交信息成功1', res.data)
											vm.$u.vuex('vuex_user_info', res.data)
											console.log('vuex_user_info = ', vm.vuex_user_info)
											let re1 = /\?code.*?(#\/)/;
											let ss = window.location.href.replace(
												re1, '#/');
											window.history.replaceState(null, null,
												ss);
											uni.navigateBack({
												delta:0
											})
											resolve()
										} else {
											console.log('获取用户登录信息失败1', res)
											reject()
										}
									})

								})()
							} else {
								reject()
							}
						})
				}
			} else {
				console.log('登录成功')
				console.log('window.location.href', window.location.href)
				let user_info = {
					grade: 0,					headimgurl: "https://thirdwx.qlogo.cn/mmopen/vi_32/M7jJGzclkA3zcTUl5KCCBnicVDNHQLKl1DCJvfGCHQrb8icY1yrjzjycvkuQOBgDDCk0RicNBKOkt50zA7t3V65sA/132",					i_film: 0,					look: 0,					manage: 1,					mobile: "",					nickname: "李多肉",					rank: "普通会员",					sex: 0,					sgs: 0,					uid: 71
				}
				if(window.location.href.indexOf('http://localhost/') !== -1) {
					console.log('本地地址')
					vm.$u.vuex('vuex_user_info', user_info)
				}
				// 已经登录过了 不做其他检查
				resolve()
			}
		}).catch((err) => {
			console.log('err=', err)
		})
	}
	// 处理token过期
	const deal_token_timeout = (pageUrl) => {
		return new Promise((resolve, reject) => {
			uni.request({
				url: vm.vuex_api_HEADER + '/index/getJwt',
				header: {
					Authorization: vm.vuex_refresh_token
				}
			}).then((res) => {
					let ans = res[1].data
					if (ans.code == 200) {
						console.log('token已过期,获取新token', res)
						console.log('保存新的token')
						vm.$u.vuex('vuex_request_token', ans.data.request_token)
						vm.$u.vuex('vuex_refresh_token', ans.data.refresh_token)
						// 获取用户信息
						vm.$u.api.get_user_social_info().then((res) => {
							if (res.code == 200) {
								vm.$u.vuex('vuex_user_info', res.data)
							}
						})
						vm.$u.utils.refresh_cur_page()
					} else {
						console.log('刷新token过期，重新登录，跳转登录链接')
						vm.$u.vuex('vuex_request_token', 'no_value')
						vm.$u.vuex('vuex_refresh_token', 'no_value')
						vm.$u.api
							.get_wechat_login_link({
								current_url: pageUrl
							})
							.then((res) => {
								if (res.code == 200) {
									window.location.href = res.data.oauth_url
								} else {
									console.log('返回登录链接失败', res)
								}
							})
					}
				})
			// end--------------------------
		})
	}
	// 用户信息丢失
	const user_info_lost = () => {
		return new Promise((resolve, reject) => {
			console.log('用户手机不存在数据')
			vm.$u.vuex('vuex_request_token', 'no_value')
			let url = window.location.href.split('#')[0]
			console.log('记录回源跳转地址', url)
			vm.$u.api
				.get_wechat_login_link({
					current_url: url
				})
				.then((res) => {
					if (res.code == 200) window.location.href = res.data.oauth_url
				})
		})
	}

	const update_user_locatin = () => {
		return new Promise((resolve, reject) => {

			console.log('重新更新经纬度')
			uni.getLocation({
				type: 'wgs84',
				success: (res) => {
					console.log('获取到位置=', res);
					console.log('当前位置的经度：' + parseFloat(res.longitude).toFixed(7));
					console.log('当前位置的纬度：' + parseFloat(res.latitude).toFixed(7));

					(async () => {
						console.log('获取位置成功，开始更新用户位置')
						let res1 = await vm.$u.api.update_euser_realtime_location({
							lon: parseFloat(res.longitude).toFixed(7),
							lat: parseFloat(res.latitude).toFixed(7),
						})
						if (res1.code == 200) {
							console.log('更新用户位置成功', res1)
							resolve()
						} else {
							console.log('更新用户位置失败', res1)
							reject()
						}
					})()

				},
				fail: (err) => {
					console.log('获取到位置失败', err)
					reject()
				}
			})
		})

	}

	const refresh_cur_page = () => {
		console.log('刷新页面')
		uni.navigateBack({
			delta: 0
		})
	}
	vm.$u.utils = {
		local_img2base64,
		auth_img2base64,
		bug_img2base64,
		login_check,
		deal_token_timeout,
		user_info_lost,
		update_user_locatin,
		refresh_cur_page
	}
}

export default {
	install
}
